﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;


namespace HttpListeenerWebDemo
{
    /// <summary>
    /// 基于HttpListener的Web服务器监听例子
    /// (使用方法:在浏览器窗口输入：  http://localhost:49152/  然后查看浏览器显示效果以及控制台输出 )
    /// </summary>
    class HttpListeenerWebDemo
    {
        static void Main(string[] args)
        {
            if (!HttpListener.IsSupported)
            {
                throw new System.InvalidOperationException("使用HttpListener监听类必须是Windows XP SP2 或者Windows Server 2003 以上系统!");
            }
            //注意前缀必须是 / 正斜杠结尾
            string[] prefixes = new string[] { "http://localhost:49152/" };
            //创建监听器
            HttpListener listener = new HttpListener();
            //增加监听的前缀
            foreach (string item in prefixes)
            {
                listener.Prefixes.Add(item);
            }
            //开始监听
            listener.Start();
            Console.WriteLine("监听中......");
            while (true)
            {
                //注意：GetContext()将阻塞线程，直到请求到达
                HttpListenerContext context = listener.GetContext();
                //取得请求对象
                HttpListenerRequest request = context.Request;
                Console.WriteLine("{0}  {1}", request.HttpMethod, request.RawUrl);
                Console.WriteLine("Accept：{0}", string.Join(",", request.AcceptTypes));
                Console.WriteLine("Accept-Language：{0}", string.Join(",", request.UserLanguages));
                Console.WriteLine("User-Agent：{0}", request.UserLanguages);
                Console.WriteLine("Accept-Language：{0}", request.UserAgent);
                Console.WriteLine("Accept-Encoding：{0}", request.Headers["Accept-Encoding"]);
                Console.WriteLine("Connection：{0}", request.KeepAlive ? "keep-Alive" : "close");
                Console.WriteLine("Host：{0}", request.UserHostName);
                Console.WriteLine("Pragma：{0}", request.Headers["Pragma"]);
                //取得回应对象
                HttpListenerResponse response = context.Response;
                //构造回应内容
                string responseString = @"<html><head><title>From HttpListener</title></head><body><h1>Hello, World !</h1></body></html>";
                //设置回应头部的内容，长度，编码
                response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseString);
                response.ContentType = "text/html;charset=UTF-8";
                //输出响应内容
                using (System.IO.Stream output = response.OutputStream)
                {
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(output))
                    {
                        writer.Write(responseString);
                    }
                }
                if (Console.KeyAvailable)
                {
                    break;
                }
            }
            //关闭监听服务器
            listener.Stop();
            Console.ReadKey();
        }

    }
}
